<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Db;
use think\facade\Config;
use redis\RedisPackage;
use app\admin\model\IndexTableModel;

if (!function_exists('get_middle_str')) {
    /**
     * 获取两个字符串中间的字符
     * @param $str
     * @param $leftStr
     * @param $rightStr
     * @return bool|string
     */
    function get_middle_str($str, $leftStr, $rightStr)
    {
        $left  = strpos($str, $leftStr);
        $right = strpos($str, $rightStr, $left);
        if ($right < $left || $left < 0) {
            return '';
        }
        return substr($str, $left + strlen($leftStr), $right - $left - strlen($leftStr));
    }
}


if (!function_exists('format_size')) {
    /**
     * 格式化文件大小单位
     * @param $size
     * @param string $delimiter
     * @return string
     */
    function format_size($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 5; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $delimiter . $units[$i];
    }
}


if (!function_exists('setting')) {
    /**
     * 设置相关助手函数
     * @param string $name
     * @param null $value
     * @return array|bool|mixed|null
     */
    function setting($name = '', $value = null)
    {
        if ($value === null && is_string($name)) {
            //获取一级配置
            if ('.' === substr($name, -1)) {
                $result = Config::pull(substr($name, 0, -1));
                if (count($result) == 0) {
                    //如果文件不存在，查找数据库
                    $result = get_database_setting(substr($name, 0, -1));
                }

                return $result;
            }
            //判断配置是否存在或读取配置
            if (0 === strpos($name, '?')) {
                $result = Config::has(substr($name, 1));
                if (!$result) {
                    //如果配置不存在，查找数据库
                    if ($name && false === strpos($name, '.')) {
                        return [];
                    }

                    if ('.' === substr($name, -1)) {

                        return get_database_setting(substr($name, 0, -1));
                    }

                    $name    = explode('.', $name);
                    $name[0] = strtolower($name[0]);

                    $result = get_database_setting($name[0]);
                    if ($result) {
                        $config = $result;
                        // 按.拆分成多维数组进行判断
                        foreach ($name as $val) {
                            if (isset($config[$val])) {
                                $config = $config[$val];
                            } else {
                                return null;
                            }
                        }

                        return $config;

                    }
                    return $result;
                }

                return $result;
            }

            $result = Config::get($name);
            if (!$result) {
                $result = get_database_setting($name);
            }
            return $result;
        }
        return Config::set($name, $value);
    }

}

if (!function_exists('get_database_setting')) {
    function get_database_setting($name)
    {
        $result = [];
        $group  = \app\common\model\SettingGroup::where('code', $name)->find();
        if ($group) {
            $result = [];
            foreach ($group->setting as $key => $setting) {
                $key_setting = [];
                foreach ($setting->content as $content) {
                    $key_setting[$content['field']] = $content['content'];
                }
                $result[$setting->code] = $key_setting;
            }
        }

        return $result;
    }
}

/**
 * @return array|false|string
 * 获取客户端ip地址
 */
function getIP()
{
    $ip = '';
    // 检查是否通过代理服务器访问
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        // 从 HTTP_CLIENT_IP 获取 IP
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // 从 HTTP_X_FORWARDED_FOR 获取 IP（可能是多个 IP 的列表）
        $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip = trim($ipList[0]); // 取第一个 IP
    } else {
        // 直接从 REMOTE_ADDR 获取 IP
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    // 确保是 IPv4 地址
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        return $ip;
    } else {
        return rand(100,999).'.'.rand(100,999).'.'.rand(100,999).'.'.rand(100,999).'xxxxx'; // 如果不是 IPv4，返回 null
    }
//    if (isset($_SERVER)) {
//        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
//            $realip = $_SERVER['HTTP_X_FORWARDED_FOR'];
//        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
//            $realip = $_SERVER['HTTP_CLIENT_IP'];
//        } else {
//            $realip = $_SERVER['REMOTE_ADDR'];
//        }
//    } else {
//        if (getenv("HTTP_X_FORWARDED_FOR")) {
//            $realip = getenv( "HTTP_X_FORWARDED_FOR");
//        } elseif (getenv("HTTP_CLIENT_IP")) {
//            $realip = getenv("HTTP_CLIENT_IP");
//        } else {
//            $realip = getenv("REMOTE_ADDR");
//        }
//    }
//    return $realip;


    global $ip;
    if (getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if(getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if(getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    else $ip = "Unknow";
    //如果获取到两个ip  去除字符串中间的空格
    return strtr($ip, array(' '=>''));
}


function getIPstr()
{
    $realip = '';
    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
                $realip .= $_SERVER['HTTP_X_FORWARDED_FOR'].',';
            }
        }
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            if(!empty($_SERVER['HTTP_CLIENT_IP'])){
                $realip .= $_SERVER['HTTP_CLIENT_IP'].',';
            }
        }
        if (isset($_SERVER['REMOTE_ADDR'])) {
            if(!empty($_SERVER['REMOTE_ADDR'])){
                $realip .= $_SERVER['REMOTE_ADDR'].',';
            }
        }
    } else {
        if(!empty(getenv("HTTP_X_FORWARDED_FOR"))){
            $realip .= getenv("HTTP_X_FORWARDED_FOR").',';
        }
        if(!empty(getenv("HTTP_CLIENT_IP"))){
            $realip .= getenv("HTTP_CLIENT_IP").',';
        }
        if(!empty(getenv("REMOTE_ADDR"))){
            $realip .= getenv("REMOTE_ADDR").',';
        }
    }
    return trim($realip,',');
}

/*
 * 判断小数点后面有几位
 */
function getFloatLength($num) {
    if(!is_numeric($num)){
        //不是数字 那就99999位
        return 99999;
    }
    $count = 0;

    $temp = explode ( '.', $num );

    if (sizeof ( $temp ) > 1) {
        $decimal = end ( $temp );
        $count = strlen ( $decimal );
    }

    return $count;
}

/**
 * 手机号中间四位变星号
 * User:@hang
 */
function hide_phone_number($phone_number) {
    return substr_replace($phone_number, '****', 3, 4);
}


/**
 * 根据秒 转换 天小时分钟
 * User:@hang
 */
function secondChanage($seconds)
{
    if(empty($seconds)) return '0小时';
    if($seconds <= 60) return '1分';
    $str = '';
    $hours = floor($seconds / 3600);
    if(!empty($hours)){
        $str .= $hours.'小时';
    }
    $minutes = floor(($seconds - ($hours * 3600)) / 60);
    if(!empty($minutes)){
        $str .= $minutes.'分';
    }
    return $str;
}

/*
 * 去除小数点后多余0
 */
function delete0($str){
    if(empty($str)){
        return '0';
    }
    if(strpos("{$str}",'.') === false){
        return $str;
    }
    $arr = explode("0",$str);
    $index = count($arr)-1;
//        dump($a);die;
    foreach ($arr as $k=>$v){
        if($arr[$index] == ''){
            unset($arr[$index]);
        }else{
            break;
        }
        $index --;
    }
    $new_str = rtrim(implode("0",$arr),".");
    return $new_str;
}


/**
 * 根据省市区code逗号拼接 获取省市区name文字拼接
 * User:@hang
 */
function areaCodeToAddress($area_code){
    if(empty($area_code)) return '暂未获取';
    $area_code_arr = explode(',',$area_code);
    $sheng = '';$shi = '';$qu = '';
    $IndexTableModel = New IndexTableModel();
    if(isset($area_code_arr[0]) && !empty($area_code_arr[0])){
        $shengInfo = $IndexTableModel->getFind('fa_area',"`adcode` = '{$area_code_arr[0]}' and `level` = 1",'name');
        $sheng = !empty($shengInfo)?$shengInfo['name']:"-";
    }
    if(isset($area_code_arr[1]) && !empty($area_code_arr[1])){
        $shiInfo = $IndexTableModel->getFind('fa_area',"`adcode` = '{$area_code_arr[1]}' and `level` = 2",'name');
        $shi = !empty($shiInfo)?$shiInfo['name']:"-";
    }
    if(isset($area_code_arr[2]) && !empty($area_code_arr[2])){
        $quInfo = $IndexTableModel->getFind('fa_area',"`adcode` = '{$area_code_arr[2]}' and `level` = 3",'name');
        $qu = !empty($quInfo)?$quInfo['name']:"-";
    }
    return $sheng.$shi.$qu;
}

/**
 * 超出省略号代替
 * User:@hang
 */
function cutStr($str,$len,$suffix="...")
{
    if(abslength($str) <= $len){
        return $str;
    }
    if(function_exists('mb_substr')){
        if(strlen($str) > $len){
            $str= mb_substr($str,0,$len,'utf-8').$suffix;
        }
        return $str;
    }else{
        if(strlen($str) > $len){
            $str= substr($str,0,$len,'utf-8').$suffix;
        }
        return $str;
    }
}


/*
 * 过滤特殊字符
 */
function replaceSpecialChar($strParam){
    if(empty($strParam)) return '';
    $regex = array(
        "/<(\\/?)(script|i?frame|style|html|body|title|link|meta|object|\\?|\\%)([^>]*?)>/isU",
        "/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU",
        "/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile|dump/is",
        "/\/|\~|\!|\ |\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\=|\\\|\|/"
    );
    $str = preg_replace($regex,"",$strParam);//去除特殊字符
    $str = preg_replace('/\r\n|\r|\n+/', '', $str);//去除换行
    return $str;
}

//字符串去换行
function setStrHh($str)
{
    return preg_replace('/\r\n|\r|\n+/', '', $str);
}

/**
 * 验证手机验证码
 * User:@hang
 */
function validatePhoneCode($phone,$code){
    if($code == '1314') return 200;//测试直接返回成功

    if(empty($phone)) return 500;
    if(empty($code)) return 500;
    $redis = new RedisPackage();
    //判断手机验证码是否正确
    $codeInfo = $redis->get('phoneCodeadmin:'.$phone);
    if(empty($codeInfo)){
        return 500;
    }
    if($codeInfo != $code){
        return 500;
    }
//    $redis->del('phoneCodeadmin:'.$phone);
    return 200;
}

/**
 * 获取当前项目域名
 * User:@hang
 */
function getAppUrl(){
    $url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://'.$_SERVER['SERVER_NAME'].'/' : 'http://'.$_SERVER['SERVER_NAME'].'/';
    return $url;
}

/*
 * 计算字符串长度 中文也算成一个字符
 */
function abslength($str)
{
    header('Content-type:text/html;charset=utf-8');
    if(empty($str)){
        return 0;
    }
    if(function_exists('mb_strlen')){
        return mb_strlen($str,'utf-8');
    }
    else {
        preg_match_all("/./u", $str, $ar);
        return count($ar[0]);
    }
}


// 自定义排序函数
function compareAges($a, $b) {
    if ($a['px'] == $b['px']) {
        return 0;
    }
    return ($a['px'] > $b['px']) ? -1 : 1;
}


/**
 * 查询包含自己在内的所有下级用户
 * User:@hang
 */
function getFemaleSubordinates($memberId) {
    // 结果数组
    $result = [];
    // 已访问的节点记录（防止循环邀请）
    $visited = [];
    $result[] = $memberId;//用户ID数组合集
    $result_mex[] = 2;//用户性别数组合集

    // 待处理队列（初始为自身ID）
    $queue = [$memberId];
    $visited[$memberId] = true; // 标记自身已访问

    // 迭代处理队列中的每个节点
    while (!empty($queue)) {
        // 批量查询当前队列中所有节点的直接下级
        $children = Db::table('fa_member')
            ->field('member_id, me_sex, me_status')
            ->where('me_parent', 'in', $queue)
//            ->where('me_status', 1)
//            ->where('me_sex', 1)
            ->select();

        // 清空当前队列（已处理）
        $queue = [];
        // 处理每个子节点
        foreach ($children as $child) {
            $childId = $child['member_id'];
            // 如果节点已被访问过，则跳过（防止循环）
            if (isset($visited[$childId])) {
                continue;
            }
            // 标记节点为已访问
            $visited[$childId] = true;
            // 加入结果集
            $result[] = $child['member_id'];
            $result_mex[] = $child['me_sex'];
            // 将子节点加入队列，继续处理其下级
            $queue[] = $childId;
        }
    }
    return ['member_id_str'=>array_unique($result),'member_sex_str'=>$result_mex];
}


/**
 * 获取某用户的最顶级上级
 * User:@hang
 */
function getDjParent($member_id)
{
    $Parent = ['dj_member_id'=>0,'bz_name'=>''];
    if(empty($member_id)) return $Parent;
    $IndexTableModel = New IndexTableModel();
    $z_member_id = $member_id;
    for ($i = 0; $i < 10; ++$i) {
        //往上找
        $membmerInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$z_member_id}'",'member_id,me_parent,bz_name');
        if(!empty($membmerInfo)){
            if(!empty($membmerInfo['me_parent'])){
                $z_member_id = $membmerInfo['me_parent'];
            }else{
                return $i == 0?['dj_member_id'=>0,'bz_name'=>'']:['dj_member_id'=>$z_member_id,'bz_name'=>$membmerInfo['bz_name']];
            }
        }
    }
    return ['dj_member_id'=>0,'bz_name'=>''];
}





